<?php
/**
*
* Data module for user fields
*
* @package	VirtueMart
* @subpackage Userfields
* @author RolandD
* @author Oscar van Eijk
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: userfields.php 3369 2011-05-25 21:46:50Z impleri $
*/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

// Load the model framework
jimport( 'joomla.application.component.model');

// Load the helpers
if(!class_exists('ParamHelper')) require(JPATH_COMPONENT.DS.'helpers'.DS.'paramhelper.php');

if(!class_exists('VmModel'))require(JPATH_COMPONENT.DS.'helpers'.DS.'vmmodel.php');

/**
 * Model class for user fields
 *
 * @package	VirtueMart
 * @subpackage Userfields
 * @author RolandD
 */
class VirtueMartModelUserfields extends VmModel {

	/** @var object paramater parsers */
	var $_params;
	/** @var array type=>fieldname with formfields that are saved as parameters */
	var $reqParam;

	/**
	 * constructs a VmModel
	 * setMainTable defines the maintable of the model
	 * @author Max Milbers
	 */
	function __construct() {
		parent::__construct();
		$this->setMainTable('userfields');

		$this->setToggleName('required');
		$this->setToggleName('registration');
		$this->setToggleName('shipping');
		$this->setToggleName('account');
		// Instantiate the Helper class
		$this->_params = new ParamHelper();

		// Form fields that must be translated to parameters
		$this->reqParam = array (
			 'age_verification' => 'minimum_age'
			,'euvatid'          => 'virtuemart_shoppergroup_id'
			,'webaddress'       => 'webaddresstype'
		);
	}

//	/**
//	 * Constructor for the userfields model.
//	 *
//	 * The userfield ID is read and detmimined if it is an array of ids or just one single id.
//	 */
//	function __construct()
//	{
//		parent::__construct();
//
//
////		// Get the pagination request variables
////		$mainframe = JFactory::getApplication() ;
////		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
////		$limitstart = $mainframe->getUserStateFromRequest(JRequest::getVar('option').JRequest::getVar('view').'.limitstart', 'limitstart', 0, 'int');
////
////		// Set the state pagination variables
////		$this->setState('limit', $limit);
////		$this->setState('limitstart', $limitstart);
////
////		// Get the (array of) order status ID(s)
////		$idArray = JRequest::getVar('cid',  0, '', 'array');
////		$this->setId((int)$idArray[0]);
//
//		// Instantiate the Helper class
//		$this->_params = new ParamHelper();
//
//
//		// Form fields that must be translated to parameters
//		$this->reqParam = array (
//			 'age_verification' => 'minimum_age'
//			,'euvatid'          => 'virtuemart_shoppergroup_id'
//			,'webaddress'       => 'webaddresstype'
//		);
//	}

	/**
	* Prepare a user field for database update
	*/
	public function prepareFieldDataSave($fieldType, $fieldName, $value=null, $post) {
//		$post = JRequest::get('post');

		switch(strtolower($fieldType)) {
			case 'webaddress':
				if (isset($post[$fieldName."Text"]) && ($post[$fieldName."Text"])) {
					$oValuesArr = array();
					$oValuesArr[0] = str_replace(array('mailto:','http://','https://'),'', $value);
					$oValuesArr[1] = str_replace(array('mailto:','http://','https://'),'', $post[$fieldName."Text"]);
					$value = implode("|*|",$oValuesArr);
				}
				else {
					$value = str_replace(array('mailto:','http://','https://'),'', $value);
				}
				break;
			case 'email':
				$value = str_replace(array('mailto:','http://','https://'),'', $value);
				break;
			case 'multiselect':
			case 'multicheckbox':
			case 'select':
				if (is_array($value)) $value = implode("|*|",$value);
				break;
			case 'age_verification':
				$value = JRequest::getInt('birthday_selector_year')
							.'-'.JRequest::getInt('birthday_selector_month')
							.'-'.JRequest::getInt('birthday_selector_day');
				break;
			default:
				break;
		}
		return $value;
	}


	/**
	 * Gets the total number of userfields
	 *
	 * @return int Total number of userfields in the database
	 */
	function _getTotal()
	{
		if (empty($this->_total)) {
			$query = $this->_getListQuery();
			$this->_total = $this->_getListCount($query);
	}
		return $this->_total;
	}

	/**
	 * Retrieve the detail record for the current $id if the data has not already been loaded.
	 */
	function getUserfield()
	{
		if (empty($this->_data)) {
			$this->_data = $this->getTable('userfields');
			$this->_data->load((int)$this->_id);
		}

		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_id = 0;
			$this->_data = null;
		}

		// Parse the parameters, if any
		$this->_params->parseParam($this->_data->params);

		return $this->_data;
	}

	/**
	 * Retrieve the value records for the current $id if available for the current type
	 *
	 * @return array List wil values, or an empty array if none exist
	 */
	function getUserfieldValues()
	{
		$this->_data = $this->getTable('userfield_values');
		if ($this->_id > 0) {
			$query = 'SELECT * FROM `#__vm_userfield_values` WHERE `fieldid` = ' . $this->_id
				. ' ORDER BY `ordering`';
			$_userFieldValues = $this->_getList($query);
			return $_userFieldValues;
		} else {
			return array();
		}
	}


	/**
	 * Retrieve an array with userfield objects
	 *
	 * @param string $section The section the fields belong to (e.g. 'registration' or 'account')
	 * @param array $_switches Array to toggle these options:
	 *                         * published    published fields only (default: true)
	 *                         * required     Required fields only (default: false)
	 *                         * delimiters   Exclude delimiters (default: false)
	 *                         * captcha      Exclude Captcha type (default: false)
	 *                         * system       System fields filter (no default; true: only system fields, false: exclude system fields)
	 * @param array $_skip Array with fieldsnames to exclude. Default: array('username', 'password', 'password2', 'agreed'),
	 *                     specify array() to skip nothing.
	 * @see getUserFieldsByUser()
	 * @author Oscar van Eijk
	 * @return array
	 */
	//this is used
	public function getUserFields ($_sec = 'registration', $_switches=array(), $_skip = array('username', 'password', 'password2', 'agreed'))
	{
		$_q = 'SELECT * FROM `#__vm_userfields` WHERE 1 = 1 ';

		if( $_sec != 'bank' && $_sec != '') {
			$_q .= 'AND `'.$_sec.'`=1 ';
		} elseif ($_sec == 'bank' ) {
			$_q .= "AND name LIKE '%bank%' ";
		}

		if (($_skipBank = array_search('bank', $_skip)) !== false ) {
			$_q .= "AND name NOT LIKE '%bank%' ";
			unset ($_skip[$_skipBank]);
		}

		if(array_key_exists('published',$_switches)){
			if ($_switches['published'] !== false ) {
				$_q .= 'AND published = 1 ';
			}
		} else {
			$_q .= 'AND published = 1 ';
		}
		if(array_key_exists('required',$_switches)){
			if ($_switches['required'] === true ) {
				$_q .= "AND required = 1 ";
			}
		}
		if(array_key_exists('delimiters',$_switches)){
			if ($_switches['delimiters'] === true ) {
				$_q .= "AND type != 'delimiter' ";
			}
		}
		if(array_key_exists('captcha',$_switches)){
			if ($_switches['captcha'] === true ) {
				$_q .= "AND type != 'captcha' ";
			}
		}
		if(array_key_exists('sys',$_switches)){
			if ($_switches['sys'] === true ) {
				$_q .= "AND sys = 1 ";
			} else {
				$_q .= "AND sys = 0 ";
			}
		}

		if (count($_skip) > 0) {
			$_q .= "AND FIND_IN_SET(name, '".implode(',', $_skip)."') = 0 ";
		}
		$_q .= 'ORDER BY ordering ';
		$_fields = $this->_getList($_q);

		// We need some extra fields that are not in the userfields table. They will be hidden on the details form
		if (!in_array('address_type', $_skip)) {
			$_address_type = new stdClass();
			$_address_type->fieldid = 0;
			$_address_type->name = 'address_type';
			$_address_type->title = '';
			$_address_type->description = '' ;
			$_address_type->type = 'hidden';
			$_address_type->maxlength = 0;
			$_address_type->size = 0;
			$_address_type->required = 0;
			$_address_type->ordering = 0;
			$_address_type->cols = 0;
			$_address_type->rows = 0;
			$_address_type->value = '';
			$_address_type->default = 'BT';
			$_address_type->published = 1;
			$_address_type->registration = 1;
			$_address_type->shipping = 0;
			$_address_type->account = 1;
			$_address_type->readonly = 0;
			$_address_type->calculated = 0;
			$_address_type->sys = 0;
			$_address_type->virtuemart_vendor_id = 1;
			$_address_type->params = '';
			$_fields[] = $_address_type;
		}

		return $_fields;
	}


	/**
	 * Translate arrays form userfield_values to the format expected by the table class.
	 *
	 * @param array $titles List of titles from the formdata
	 * @param array $values List of values from the formdata
	 * @param int $virtuemart_userfield_id ID of the userfield to relate
	 * @return array Data to bind to the userfield_values table
	 */
	private function postData2FieldValues($titles, $values, $virtuemart_userfield_id){

		$_values = array();
		if (is_array($titles) && is_array($values)) {
			for ($i=0; $i < count($titles) ;$i++) {
				if (empty($titles[$i])) {
					continue; // Ignore empty fields
				}
				$_values[] = array(
					 'virtuemart_userfield_id'    => $virtuemart_userfield_id
					,'fieldtitle' => $titles[$i]
					,'fieldvalue' => $values[$i]
					,'ordering'   => $i
				);
			}
		}
		return $_values;
	}

	/**
	 * Get the column name of a given fieldID
	 * @param $_id integer Field ID
	 * @return string Fieldname
	 */
	function getNameByID($_id)
	{
		$_sql = 'SELECT name '
				. 'FROM `#__virtuemart_userfields`'
				. "WHERE virtuemart_userfield_id = $_id";

		$_v = $this->_getList($_sql);
		return ($_v[0]->name);
	}

	/**
	 * Delete all record ids selected
	 *
	 * @return boolean True is the remove was successful, false otherwise.
	 */
	function remove()
	{
		$fieldIds   = JRequest::getVar('cid',  0, '', 'array');
		$field      =& $this->getTable('userfields');
		$value      =& $this->getTable('userfield_values');
		$userinfo   =& $this->getTable('userinfos');
		$orderinfo  =& $this->getTable('order_userinfos');

		foreach($fieldIds as $fieldId) {
			$_fieldName = $this->getNameByID($fieldId);

			// Alter the user_info table
			if (!$userinfo->_modifyColumn ('DROP', $_fieldName)) {
				$this->setError($userinfo->getError());
				return false;
			}

			// Alter the order_userinfo table
			if (!$orderinfo->_modifyColumn ('DROP', $_fieldName)) {
				$this->setError($orderinfo->getError());
				return false;
			}

			if (!$field->delete($fieldId)) {
				$this->setError($field->getError());
				return false;
			}
			if (!$value->delete($fieldId)) {
				$this->setError($field->getError());
				return false;
			}
		}

		return true;
	}

	/**
	 * Retrieve a list of userfields from the database.
	 *
	 * @return object List of userfield objects
	 */
	function getUserfieldsList()
	{
		if (!$this->_data) {
			$query = $this->_getListQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}
		return $this->_data;
	}

	/**
	 * Get the SQL Ordering statement
	 *
	 * @return string text to add to the SQL statement
	 */
	function _getOrdering()
	{
		$option = JRequest::getCmd( 'option');
		$mainframe = JFactory::getApplication() ;

		$filter_order_Dir = $mainframe->getUserStateFromRequest( $option.JRequest::getVar('view').'filter_order_Dir', 'filter_order_Dir', 'asc', 'word' );
		$filter_order     = $mainframe->getUserStateFromRequest( $option.JRequest::getVar('view').'filter_order', 'filter_order', 'ordering', 'cmd' );

		return (' ORDER BY '.$filter_order.' '.$filter_order_Dir);
	}

	/**
	 * If a filter was set, get the SQL WHERE clase
	 *
	 * @return string text to add to the SQL statement
	 */
	function _getFilter()
	{
		$db = JFactory::getDBO();
		if (JRequest::getVar('search', false)) {
			return (' WHERE `name` LIKE ' .$db->Quote('%'.JRequest::getVar('search').'%'));
		}
		return ('');
	}

	/**
	 * Build the query to list all Userfields
	 *
	 * @return string SQL query statement
	 */
	function _getListQuery ()
	{
		$query = 'SELECT * FROM `#__virtuemart_userfields` ';
		$query .= $this->_getFilter();
		$query .= $this->_getOrdering();
		return ($query);
	}

	// /**
	 // * Change the ordering of an Userfield
	 // *
	 // * @return boolean True on success
	 // */
	// function move($direction)
	// {
		// $table =& $this->getTable('userfields');
		// if (!$table->load($this->_id)) {
			// $this->setError($this->_db->getErrorMsg());
			// return false;
		// }
		// if (!$table->move($direction)){
			// $this->setError($this->_db->getErrorMsg());
			// return false;
		// }

		// return true;
	// }

	// /**
	 // * Reorder the Userfields
	 // *
	 // * @return boolean True on success
	 // */
	// function saveorder($cid = array(), $order)
	// {
		// $table =& $this->getTable('userfields');

		//update ordering values
		// for( $i=0; $i < count($cid); $i++ )
		// {
			// $table->load( (int) $cid[$i] );
			// if ($table->ordering != $order[$i])
			// {
				// $table->ordering = $order[$i];
				// if (!$table->store()) {
					// $this->setError($this->_db->getErrorMsg());
					// return false;
				// }
			// }
		// }

		// return true;
	// }
}

// No closing tag